package com.platform.modular.controller;

import com.platform.common.model.Result;
import com.platform.common.utils.R;
import com.platform.modular.feign.account.UserWechatFeignService;
import com.platform.modular.model.account.dto.DecodeUserMobileDTO;
import com.platform.modular.model.account.dto.UserWechatInfoDTO;
import com.platform.modular.model.account.vo.MobileLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yifei.han
 * @version 1.0
 * @className LoginController
 * @description 小程序用户登录模块
 * @date 2022/3/9
 */
@Slf4j
@RestController
@RequestMapping("miniprogram/login")
public class LoginController {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private UserWechatFeignService userWechatFeignService;

    /**
     *
     * @param code
     * @return
     */
    @RequestMapping(value = "/obtainUserWechatOpenid")
    public Result obtainUserWechatOpenid(@RequestBody String code, HttpServletRequest request) {
        String appId = request.getHeader("appId");
        String openid = userWechatFeignService.obtainUserWechatOpenid(code, appId);
        Map<String, Object> resultData = new HashMap<>();
        resultData.put("openid", openid);
        return Result.ok().setResult(resultData);
    }


    @RequestMapping(value = "/saveUserWechatInfo")
    public Result saveUserWechatInfo(@RequestBody UserWechatInfoDTO userWechatInfoDTO) throws Exception {
        userWechatFeignService.saveUserWechatInfo(userWechatInfoDTO);
        return Result.ok();
    }

    @RequestMapping(value = "/obtainUserWechatMobile")
    public Result obtainUserWechatMobile(@RequestBody DecodeUserMobileDTO decodeUserMobileForm) {
        R r = userWechatFeignService.obtainUserWechatMobile(decodeUserMobileForm);
        if ((int)r.get("code") != 0) {
            return Result.fail(r.get("msg").toString());
        }
        MobileLoginVO mobileLoginVO = new MobileLoginVO();
        mobileLoginVO.setMobile(r.get("token").toString());
        mobileLoginVO.setToken(r.get("mobile").toString());
        return Result.ok().setResult(mobileLoginVO);
    }


}
